﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DependencyInject_host.service;
using DependencyInject_host.service.sub;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace DependencyInject_host
{
    internal class Program
    {
        static void Main(string[] args)
        {   /*
        https://learn.microsoft.com/zh-cn/dotnet/core/extensions/dependency-injection-usage
        */
            var builder = Host.CreateApplicationBuilder(args);

            builder.Services.AddScoped<IExampleScopedService, ExampleScopedService>();

            builder.Services.AddSingleton<IExampleSingletonService, ExampleSingletonService>();

            builder.Services.AddTransient<IExampleTransientService, ExampleTransientService>();

            builder.Services.AddTransient<ServiceLifetimeReporter>();

            var host = builder.Build();

            ExemplifyServiceLifetime(host.Services, "Lifetime 1");
            ExemplifyServiceLifetime(host.Services, "Lifetime 2");

            host.Run();
        }


        static void ExemplifyServiceLifetime(IServiceProvider hostProvider, string lifetime)
        {
            IServiceScope serviceScope = hostProvider.CreateScope();
            IServiceProvider provider = serviceScope.ServiceProvider;
            ServiceLifetimeReporter logger = provider.GetRequiredService<ServiceLifetimeReporter>();
            logger.ReportServiceLifetimeDetails(
                $"{lifetime}: Call 1 to provider.GetRequiredService<ServiceLifetimeReporter>()");

            Console.WriteLine("...");

            logger = provider.GetRequiredService<ServiceLifetimeReporter>();
            logger.ReportServiceLifetimeDetails(
                $"{lifetime}: Call 2 to provider.GetRequiredService<ServiceLifetimeReporter>()");

            Console.WriteLine();
        }
    }
}